<?php

namespace app\kaoqin\api;

use app\common\logic\Department;
use app\common\logic\FullUser;
use app\common\logic\OldRecord;
use app\common\logic\RecordSumToday;
use app\common\logic\User;

class All extends Common
{
    public function index()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $uid = getUid();

        $kq_hide_userid = c('kq_hide_userid');
        if (!is_array($kq_hide_userid)) $kq_hide_userid = [$kq_hide_userid];

        $where = ['id' => ['not in', $kq_hide_userid]];

        $kq_show_all_userid = c('kq_show_all_userid');
        if (!is_array($kq_show_all_userid)) $kq_show_all_userid = [$kq_show_all_userid];

        if (!in_array($uid, $kq_show_all_userid)) {
            $local_user = User::get(['userid' => $uid]);
            $dept_pid = Department::getPidById($local_user['department']);
            $child_id = Department::getChildIds($dept_pid);

            $where['pid'] = ['in', $child_id];
        }

        $ret = RecordSumToday::getAllWorkInfoToday($where);
        if ($ret === false)
            return $this->error('发生错误');

        return $this->success($ret);
    }

    public function count()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $uid = getUid();
        $dept_id = User::where(['userid' => $uid])->value('department');
        $pid = Department::getPidById($dept_id);
        $child_ids = Department::getChildIds($pid);

        $root_userid = is_array(c('root_userid')) ? c('root_userid') : [c('root_userid')];

        $where = [];
        if (!in_array($uid, $root_userid) && !empty($child_ids))
            $where['pid'] = ['in', $child_ids];

        $record_sum_today = RecordSumToday::where($where)->field('id,extattr,count')->select();

        $working = [];
        $learning = [];
        $xiuxi = [];
        $xiujia = [];

        foreach ($record_sum_today as $value) {
            if (in_array($value['id'], c('kq_hide_userid')))
                continue;

            if ($value['count'] == 0) {
                $xiujia[] = $value['id'];
            } else {
                if ($value['count'] % 2 == 0) {
                    $xiuxi[] = $value['id'];
                } else if ($value['count'] % 2 == 1) {
                    if (!empty($value['extattr'])) {
                        $extattr = unserialize($value['extattr']);
                        if (!isset($extattr['attrs']) || empty($extattr['attrs'])) {
                            $working[] = $value['id'];
                        } else {
                            foreach ($extattr['attrs'] as $val) {
                                if ($val['name'] == '身份' && $val['value'] == '学生') {
                                    $learning[] = $value['id'];
                                }
                            }
                        }
                    } else {
                        $working[] = $value['id'];
                    }
                }
            }
        }

        $top[] = ['id' => 'working', 'name' => '工作中', 'count' => count($working)];
        $top[] = ['id' => 'learning', 'name' => '学习中', 'count' => count($learning)];
        $top[] = ['id' => 'xiuxi', 'name' => '休息中', 'count' => count($xiuxi)];
        $top[] = ['id' => 'xiujia', 'name' => '休假中', 'count' => count($xiujia)];

        $where = [];
        if (!in_array($uid, $root_userid) && !empty($child_ids))
            $where['depart_id'] = ['in', $child_ids];

        $users = FullUser::where($where)->group('depart_name')->order('depart_code')
            ->field('group_concat(user_id) user_ids,depart_id,depart_name,count(distinct user_id) count')->select();

        $show = array_merge($working, $learning);
        $bottom = [];
        foreach ($users as $val) {
            $user_ids = explode(',', $val['user_ids']);

            if (empty($user_ids)) $same = 0;
            else $same = count(array_intersect($show, $user_ids));

            $desc = $same . '/' . $val['count'];
            $depart_name = $val['depart_name'];
            $depart_id = $val['depart_id'];

            $bottom[] = ['id' => $depart_id, 'name' => $depart_name, 'count' => $desc];
        }

        $ret['top'] = $top;
        $ret['bottom'] = $bottom;

        return $this->success($ret);
    }

    public function lists()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');
        $uid = getUid();

        $dept_id = User::where(['userid' => $uid])->value('department');
        $pid = Department::getPidById($dept_id);
        $child_ids = Department::getChildIds($pid);
        $root_userid = is_array(c('root_userid')) ? c('root_userid') : [c('root_userid')];

        if (!isset($req['id']) || empty($req['id']))
            return $this->error('请选择要展开的分组');

        $id = $req['id'];

        $where = '';
        if (!in_array($uid, $root_userid) && !empty($child_ids))
            $where .= "pid in (" . implode(',', $child_ids) . ") and";

        if ($id == 'working') {
            $where .= " count <> 0 and count %2 = 1 and extattr = ''";
        } elseif ($id == 'learning') {
            $where .= " count <> 0 and count %2 = 1 and extattr <> ''";
        } elseif ($id == 'xiuxi') {
            $where .= " count <> 0 and count %2 = 0";
        } elseif ($id == 'xiujia') {
            $where .= " count = 0";
        } else {
            $where .= " dept_id = {$id}";
        }

        $record_sum_today = RecordSumToday::getList($where, 'id,avatar,extattr,name,dept,count');
        if (empty($record_sum_today)) return $this->success($record_sum_today);

        $list = $record_sum_today['list'];
        foreach ($list as $key => $val) {
            $user_id = $val['id'];
            $time = date('Y-m-d');

            //返回当天打卡记录
            $work_log = OldRecord::getWorkLog($user_id, $time);

            $status = '';
            if (count($work_log) == 0) $status = 'xiujia';
            else {
                if (count($work_log) % 2 == 0) $status = 'xiuxi';
                else if (count($work_log) % 2 == 1) {
                    if (!empty($recordSumToday['extattr'])) {
                        $extattr = unserialize($recordSumToday['extattr']);
                        if (!isset($extattr['attrs']) || empty($extattr['attrs'])) {
                            $status = 'working';
                        } else {
                            $status = 'learning';
                        }
                    } else $status = 'working';
                }
            }

            $list[$key]['status'] = $status;

            foreach ($work_log as $k => $v) {
                if ($k % 2 == 0) {
                    $work_log[$k]['status'] = 'come';
                    $work_log[$k]['time_diff'] = 0;
                } else {
                    $work_log[$k]['status'] = 'leave';
                    $work_log[$k]['time_diff'] = time_diff2hour($v['time_unix'] - $work_log[$k - 1]['time_unix']);
                }
            }

            //返回到岗时间&工作时长
            if (count($work_log) > 0) {
                $first_work_time = $work_log[0]['time'];
                $list[$key]['first_time'] = $first_work_time;

                $work_time_total = $this->getWorkTime($time, $work_log);
                $list[$key]['total_time'] = $work_time_total;
            } else {
                $list[$key]['first_time'] = "尚未签到";
                $list[$key]['total_time'] = 0;
            }
        }
        $record_sum_today['list'] = $list;

        return $this->success($record_sum_today);
    }

    /**
     * 根据日期和打卡记录返回工作时长
     * @param $time
     * @param $work_log
     * @return string
     * @author wb <pithyone@vip.qq.com>
     */
    private function getWorkTime($time, $work_log)
    {
        $time_diff = 0;
        $odd = array();
        $even = array();

        foreach ($work_log as $k => $v) {
            if ($k % 2 == 0) $odd[] = $v;
            else $even[] = $v;
        }

        foreach ($odd as $k => $v) {
            if (!empty($even[$k])) {
                $time_diff += ($even[$k]['time_unix'] - $odd[$k]['time_unix']);
            } else {
                $today = date('Y-m-d', time());
                if ($time == $today)
                    $time_diff += (time() - $odd[$k]['time_unix']);
                else {
//                    TODO: 非当天&奇数打卡->操作
//                    $time_end = date('Y-m-d 23:59:59', strtotime($time));
//                    $time_diff += (strtotime($time_end) - $odd[$k]['time_unix']);
                }
            }
        }


        return $time_diff ? time_diff2string($time_diff) : $time_diff;
    }

    public function search()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');
        $uid = getUid();

        $dept_id = User::where(['userid' => $uid])->value('department');
        $pid = Department::getPidById($dept_id);
        $child_ids = Department::getChildIds($pid);
        $root_userid = is_array(c('root_userid')) ? c('root_userid') : [c('root_userid')];

        $where = '';
        if (!in_array($uid, $root_userid) && !empty($child_ids))
            $where .= "pid in (" . implode(',', $child_ids) . ") and";

        if (isset($req['keyword']) && !empty($req['keyword']) && !stristr($req['keyword'], '%')) {
            $where .= " (name like '%{$req['keyword']}%' or dept like '%{$req['keyword']}%')";

            if (isset($req['id']) && !empty($req['id']))
                $where .= " or dept_id = {$req['id']}";

            $list = RecordSumToday::where($where)->field('id,name,dept_id,dept,count')->order('code,id')->select();

            $ret = [];
            foreach ($list as $k => $val) {
                $dept = $val['dept'];
                $count = $val['count'];

                $ret[$dept]['id'] = $val['dept_id'];
                $ret[$dept]['name'] = $dept;

                $status = '';
                if ($count == 0) $status = 'xiujia';
                else {
                    if ($count % 2 == 0) $status = 'xiuxi';
                    else if ($count % 2 == 1) {
                        if (!empty($recordSumToday['extattr'])) {
                            $extattr = unserialize($recordSumToday['extattr']);
                            if (!isset($extattr['attrs']) || empty($extattr['attrs'])) {
                                $status = 'working';
                            } else {
                                $status = 'learning';
                            }
                        } else $status = 'working';
                    }
                }

                $val['status'] = $status;
                $ret[$dept]['list'][] = $val;
            }

            return $this->success(array_values($ret));
        }

        return $this->success([]);
    }
}